namespace mrs;

using Microsoft.AspNetCore.Hosting;

public interface IConfigService
{
    SystemConfig GetConfig();
    void ReloadConfig();
    T GetSection<T>(string sectionName) where T : new();
}

public class ConfigService : IConfigService
{
    public ConfigService(ILogger<ConfigService> logger, IWebHostEnvironment env)
    {
        _logger = logger;

        // 根据环境确定配置文件路径
        var configDir = Path.Combine(env.ContentRootPath, "config");
        _configFilePath = Path.Combine(configDir, "config.json");

        // 确保目录存在
        if (!Directory.Exists(configDir))
        {
            Directory.CreateDirectory(configDir);
            _logger.LogInformation("Created system directory: {ConfigDir}", configDir);
        }

        LoadConfig();
    }

    private readonly ILogger<ConfigService> _logger;
    private SystemConfig _config;
    private readonly string _configFilePath;
    private readonly object _lockObject = new();

    public SystemConfig GetConfig()
    {
        lock (_lockObject)
        {
            return _config;
        }
    }

    public void ReloadConfig()
    {
        try
        {
            LoadConfig();
            _logger.LogInformation("Configuration reloaded successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to reload configuration");
            throw;
        }
    }

    public T GetSection<T>(string sectionName) where T : new()
    {
        lock (_lockObject)
        {
            var section = typeof(SystemConfig).GetProperty(sectionName)?.GetValue(_config);
            if (section is T typedSection)
            {
                return typedSection;
            }

            // 如果找不到对应的节，返回默认值
            _logger.LogWarning("Section {SectionName} not found or type mismatch, returning default", sectionName);
            return new T();
        }
    }

    private void LoadConfig()
    {
        try
        {
            if (!File.Exists(_configFilePath))
            {
                _logger.LogWarning("Config file not found at {ConfigFilePath}, using default configuration", _configFilePath);
                _config = new SystemConfig();
                return;
            }

            var json = File.ReadAllText(_configFilePath);
            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                ReadCommentHandling = JsonCommentHandling.Skip,
                AllowTrailingCommas = true
            };

            var config = JsonSerializer.Deserialize<SystemConfig>(json, options);
            _config = config ?? new SystemConfig();

            _logger.LogInformation("Configuration loaded from {ConfigFilePath}", _configFilePath);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error loading configuration from {ConfigFilePath}", _configFilePath);
            _config = new SystemConfig();
        }
    }


    // {{END}}
}